﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace Jodell.Transport.Modbus
{
    public class CrcUtil
    {
        private static readonly UInt16[] crc_ta = new UInt16[16] { 0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401, 0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400, };

        /// <summary>Crc校验</summary>
        /// <param name="data"></param>
        /// <param name="offset">偏移</param>
        /// <param name="count">数量</param>
        /// <returns></returns>
        public static UInt16 Crc(IEnumerable<byte> data, Int32 offset = 0, Int32 count = 0)
        {
            if (data == null || data.Count() < 1) return 0;

            UInt16 u = 0xFFFF;
            Byte b;

            if (count == 0)
                count = data.Count() - offset;

            for (var i = offset; i < offset + count; i++)
            {
                b = data.ElementAt(i);
                u = (UInt16)(crc_ta[(b ^ u) & 15] ^ (u >> 4));
                u = (UInt16)(crc_ta[((b >> 4) ^ u) & 15] ^ (u >> 4));
            }

            return u;
        }
    }

}
